import sys
import os
from PyQt5.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton,
    QTabWidget, QListWidget, QListWidgetItem, QFileDialog, QInputDialog,
    QLabel
)
from PyQt5.QtCore import QThread, pyqtSignal, Qt
import yt_dlp
import textwrap


# 定义一个后台下载线程类，用来执行下载任务
class DownloadThread(QThread):
    progress_signal = pyqtSignal(int, str)  # 用来更新进度和下载速度
    finished_signal = pyqtSignal(str)  # 下载完成后发送信号
    title_signal = pyqtSignal(str)  # 用来发送视频标题

    def __init__(self, url, save_path):
        super().__init__()
        self.url = url
        self.save_path = save_path
        self.title = ""

    def run(self):
        # 获取视频标题
        ydl_opts = {'quiet': True, 'extract_flat': True}  # 不下载任何文件，只提取视频信息
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            info = ydl.extract_info(self.url, download=False)
            self.title = info.get('title', '未知标题')

        # 发射信号传递视频标题
        self.title_signal.emit(self.title)

        # 下载设置
        ydl_opts = {
            'format': 'bestvideo+bestaudio/best',  # 最好的视频和音频格式
            'outtmpl': os.path.join(self.save_path, '%(title)s.%(ext)s'),  # 保存路径
            'writeautomaticsub': True,  # 自动下载字幕
            'progress_hooks': [self.progress_hook],  # 设置进度钩子
            'quiet': False,  # 关闭静默模式，显示下载过程
            'nocheckcertificate': True,
            'force_ipv4': True,
            'http_headers': {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                              '(KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
            },
            'cookiefile': 'cookies.txt',
            'writesubtitles': True,  # 下载自动生成的字幕
            'subtitleslangs': ['zh'],  # 下载中文字幕
        }

        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            ydl.download([self.url])  # 下载视频

    def progress_hook(self, progress):
        # 进度回调
        if 'downloaded_bytes' in progress and progress.get('total_bytes'):
            percent = int(progress['downloaded_bytes'] / progress['total_bytes'] * 100)
            speed = (progress.get('speed') or 0) / 1024  # 防止 None 导致崩溃
            self.progress_signal.emit(percent, f"{speed:.2f} KB/s")

        # 下载完成
        if progress.get('status') == 'finished':
            self.finished_signal.emit(progress.get('filename'))


# 定义视频下载任务项的显示控件
class DownloadItemWidget(QWidget):
    def __init__(self, title):
        super().__init__()
        self.title = title
        self.init_ui()

    def init_ui(self):
        self.layout = QHBoxLayout()

        # 截断标题，超过20个字符显示“...”后缀
        wrapped_title = textwrap.shorten(self.title, width=50, placeholder="...")
        self.title_label = QLabel(wrapped_title)
        self.percent_label = QLabel("0%")
        self.speed_label = QLabel("速度: 0 KB/s")

        self.layout.addWidget(self.title_label)
        self.layout.addWidget(self.percent_label)
        self.layout.addWidget(self.speed_label)
        self.setLayout(self.layout)
        self.setStyleSheet("""
            QWidget {
                font-family: Arial, Helvetica, sans-serif;
                font-size: 12px;
                color: #333;
                background-color: #f5f5f5;
                border-radius: 5px;
            }

            QPushButton {
                background-color: #4CAF50;
                color: white;
                border: none;
                padding: 10px 20px;
                font-size: 14px;
                border-radius: 5px;
                cursor: pointer;
                transition: background-color 0.3s;
            }

            QPushButton:hover {
                background-color: #45a049;
            }

            QTabWidget::pane {
                border: 1px solid #ccc;
                background-color: #fff;
                border-radius: 5px;
            }

            QTabBar::tab {
                background-color: #4CAF50;
                color: white;
                padding: 10px;
                font-size: 14px;
                border-top-left-radius: 5px;
                border-top-right-radius: 5px;
            }

            QTabBar::tab:selected {
                background-color: #388E3C;
            }

            QTabWidget::tab-bar {
                alignment: center;
            }

            QListWidget {
                background-color: white;
                border-radius: 5px;
                border: 1px solid #ccc;
                padding: 10px;
                font-size: 12px;
                color: #333;
            }

            QListWidget::item {
                background-color: #fff;
                border: 1px solid #ccc;
                margin-bottom: 5px;
                border-radius: 5px;
                padding: 5px;
            }

            QListWidget::item:selected {
                background-color: #4CAF50;
                color: white;
            }

            QLabel {
                font-size: 14px;
                color: #333;
            }

            QInputDialog {
                background-color: #fff;
            }

            QLineEdit {
                border: 1px solid #ccc;
                padding: 5px;
                font-size: 14px;
                border-radius: 5px;
            }

            QProgressBar {
                border: 1px solid #ccc;
                border-radius: 5px;
                text-align: center;
                height: 20px;
            }

            QProgressBar::chunk {
                background-color: #4CAF50;
                border-radius: 5px;
            }
        """)

    def update_progress(self, percent, speed):
        self.percent_label.setText(f"{percent}%")
        self.speed_label.setText(f"速度: {speed}")


# 主应用程序窗口
class YouTubeSubtitleApp(QWidget):
    def __init__(self):
        super().__init__()
        self.save_path = os.path.join(os.getcwd(), "Downloads")
        os.makedirs(self.save_path, exist_ok=True)
        self.init_ui()

    def init_ui(self):
        self.setWindowTitle("YouTube 字幕下载器")
        self.resize(800, 600)

        # 顶部按钮布局
        self.top_bar = QHBoxLayout()
        self.add_button = QPushButton("➕ 添加任务")
        self.settings_button = QPushButton("⚙ 设置")
        self.top_bar.addWidget(self.add_button)
        self.top_bar.addStretch()
        self.top_bar.addWidget(self.settings_button)

        # Tab 控件
        self.tabs = QTabWidget()
        self.downloading_list = QListWidget()
        self.finished_list = QListWidget()
        self.tabs.addTab(self.downloading_list, "下载中")
        self.tabs.addTab(self.finished_list, "已完成")

        # 主布局
        self.main_layout = QVBoxLayout()
        self.main_layout.addLayout(self.top_bar)
        self.main_layout.addWidget(self.tabs)
        self.setLayout(self.main_layout)

        # 信号连接
        self.add_button.clicked.connect(self.add_task)
        self.settings_button.clicked.connect(self.select_download_path)

        # 设置样式
        self.setStyleSheet(""" ...""")  # 留下原先的QSS样式

    def add_task(self):
        dialog = QInputDialog(self)
        dialog.setLabelText("请输入 YouTube 视频链接：")
        dialog.setTextValue("")
        dialog.resize(640, 100)  # 设置输入框的大小
        ok = dialog.exec_()

        url = dialog.textValue()
        if ok and url:
            # 创建下载线程
            download_thread = DownloadThread(url, self.save_path)
            download_thread.title_signal.connect(self.on_title_received)
            download_thread.progress_signal.connect(self.update_progress)
            download_thread.finished_signal.connect(self.on_download_finished)
            download_thread.start()

            # 创建列表项
            item_widget = DownloadItemWidget("正在获取标题...")
            list_item = QListWidgetItem(self.downloading_list)
            list_item.setSizeHint(item_widget.sizeHint())
            self.downloading_list.addItem(list_item)
            self.downloading_list.setItemWidget(list_item, item_widget)

    def on_title_received(self, title):
        # 更新标题
        item_widget = self.downloading_list.itemWidget(self.downloading_list.item(0))
        item_widget.title = title
        item_widget.title_label.setText(textwrap.shorten(title, width=50, placeholder="..."))

    def update_progress(self, percent, speed):
        item_widget = self.downloading_list.itemWidget(self.downloading_list.item(0))
        item_widget.update_progress(percent, speed)

    def on_download_finished(self, filename):
        finished_item = QListWidgetItem(f"下载完成: {filename}")
        self.finished_list.addItem(finished_item)

    def select_download_path(self):
        directory = QFileDialog.getExistingDirectory(self, "选择下载保存路径", self.save_path)
        if directory:
            self.save_path = directory


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = YouTubeSubtitleApp()
    window.show()
    sys.exit(app.exec_())
